import java.io.IOException;
import java.io.PrintWriter;
import redis.clients.jedis.Jedis;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

@WebServlet("/add_prompt")

public class AddPrompt extends BaseServlet {
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html");
        resp.setCharacterEncoding("UTF-8");

        String id = req.getParameter("id");
        String prompt = req.getParameter("prompt");
        String comment = req.getParameter("comment");

        if (prompt == null || comment == null) {
            throw new ServletException("please input all parameters");
        }

        Jedis jedis = new Jedis("localhost", 6379);
        jedis.del(id);
        jedis.close();
        // 1.在redis中删除key为此id的数据
        /*
            请完善代码
        */

        // 2.向数据库中加入prompt、comment
        addPrompt(getJDBCConnection(), id, prompt, comment);

        PrintWriter out = resp.getWriter();
        out.printf("[add]ok");
        out.close();

    }

    public void addPrompt(final Connection conn, String id, String prompt, String comment)
            throws ServletException {
        PreparedStatement stmt = null;
        try {
            /*
                请完善代码
            */
            stmt = conn.prepareStatement("INSERT INTO t_ai_painting (id, prompt, comment) VALUES (?, ?, ?)");
            stmt.setString(1, id);
            stmt.setString(2, prompt);
            stmt.setString(3, comment);
            stmt.executeUpdate();
        } catch (Exception e) {
            throw new ServletException(e);
        } finally {
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

}
